<template>
  <div class="tabs-box">
    <div class="tabs-menu">
      <el-tabs v-model="tabsMenuValue" type="card" @tab-click="tabClick" @tab-remove="tabRemove" ref="tabsMenu">
        <el-tab-pane v-for="item in tabsMenuList" :key="item.path" :label="item.title" :name="item.path" :closable="item.close">
          <template #label>
            <el-icon v-if="item.icon && tabsIcon && item.icon.indexOf('menu-')>-1" class="tabs-icon">
              <component :is="'Menu'"></component>
            </el-icon>
            <el-icon v-if="item.icon && tabsIcon" class="tabs-icon">
              <component :is="item.icon"></component>
            </el-icon>
            {{ item.title }}
          </template>
        </el-tab-pane>
      </el-tabs>
      <MoreButton />
    </div>
  </div>
</template>

<script setup lang="ts">
import Sortable from "sortablejs";
import { ref, computed, watch, onMounted } from "vue";
import { useRoute, useRouter } from "vue-router";
// import { useGlobalStore } from "@/stores/modules/global";
// import { useTabsStore } from "@/stores/modules/tabs";
// import { useAuthStore } from "@/stores/modules/auth";
import { TabsPaneContext, TabPaneName } from "element-plus";
import MoreButton from "./components/MoreButton.vue";
import { useStore } from 'vuex'
const store = useStore()
// const { ipcRenderer } = require("electron");

// declare global {
//   interface Window {
//     $gnb: any;
//   }
// }
// import { GNBEventManager } from "@/utils/event-manager";
// import {
//   closeTabOnTabPage,
//   createTabOnWindow,
//   frameDidReadyOnTabPage,
//   onCloseTab,
//   onCreateTab,
//   onSwitchTab,
//   onTabTitle,
//   switchTabOnWindow
// } from "@/utils/gnb.desktop";

const route = useRoute();
const router = useRouter();
// const tabStore = useTabsStore();
// const authStore = useAuthStore();
// const globalStore = useGlobalStore();

// GNBEventManager.shared.register();

const tabsMenuValue = ref(route.fullPath);
const tabsMenuList = computed(() => store.state.layouts.tabsMenuList);
const authMenuList = computed(() => store.state.layouts.authMenuList);
const tabsIcon = computed(() => store.state.layouts.globalState.tabsIcon);

onMounted(() => {
  tabsDrop();
  initTabs();
});

// 监听路由的变化（防止浏览器后退/前进不变化 tabsMenuValue）
watch(
  () => route.fullPath,
  () => {
    if (route.meta.isFull || route.meta?.noSave) return;
    // console.log("route.fullPath", route);
    let idx = authMenuList.value.findIndex((item: any) => item.name == route.name);
    if (idx == -1) return;
    tabsMenuValue.value = route.fullPath;
    const tabsParams = {
      icon: route.meta.icon as string,
      title: route.meta.title as string,
      path: route.fullPath,
      name: route.name as string,
      close: !route.meta.isAffix,
      isKeepAlive: route.meta.isKeepAlive as boolean
    };
    // tabStore.addTabs(tabsParams);
    store.dispatch('layouts/addTabs', tabsParams)
  },
  { immediate: true }
);
const isURL = (url: any) => {
  const regex = /^(http|https):\/\/[^ "]+$/;
  return regex.test(url);
};
// 初始化需要固定的 tabs
const initTabs = () => {
  // console.log('store.getters[layouts/flatMenuListGet]', store.getters['layouts/flatMenuListGet']);
  store.getters['layouts/flatMenuListGet'].forEach((item: any) => {

    if (item.meta.isAffix && !item.meta.isHide && !item.meta.isFull) {
      // let idx = authMenuList.value.findIndex((item: any) => item.name == route.name);
      // if (idx > -1) {
        const tabsParams = {
          icon: item.meta.icon,
          title: item.meta.title,
          path: item.path,
          name: item.name,
          close: !item.meta.isAffix,
          isKeepAlive: item.meta.isKeepAlive
        };
        // tabStore.addTabs(tabsParams);
        store.dispatch('layouts/addTabs', tabsParams)
      // }
    }
  });

  // ipcRenderer.invoke("desktop:service", { type: "frameDidReadyOnTabPage" });
  // window.$gnb.$desktop({ type: "frameDidReadyOnTabPage" });
};

type TabChangeEvent = {
  newIndex: number;
  oldIndex: number;
};
// tabs 拖拽排序
const tabsDrop = () => {
  Sortable.create(document.querySelector(".el-tabs__nav") as HTMLElement, {
    draggable: ".el-tabs__item",
    animation: 300,
    onEnd({ newIndex, oldIndex }: TabChangeEvent) {
      const tabsList = [...store.state.layouts.tabsMenuList];
      const currRow = tabsList.splice(oldIndex as number, 1)[0];
      tabsList.splice(newIndex as number, 0, currRow);
      // tabStore.setTabs(tabsList);
      store.dispatch('layouts/setTabs', tabsList)
    }
  });
};

// Tab Click
const tabClick = (tabItem: TabsPaneContext) => {
  // console.log(tabItem);
  const fullPath = tabItem.props.name as string;
  if (isURL(fullPath)) {
    // ipcRenderer.invoke("desktop:service", { type: "switchTabOnWindow", data: { id: id } });
    // window.open(fullPath);
  } else {
    router.push(fullPath);
  }
};

// Remove Tab
const tabRemove = (fullPath: TabPaneName) => {
  store.dispatch('layouts/removeTabs', { tabPath: fullPath, isCurrent: fullPath == route.fullPath })
  // tabStore.removeTabs(fullPath as string, fullPath == route.fullPath);
};
</script>

<style scoped lang="scss">
@use "./index.scss";
</style>
